package com.argrace.smart.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.argrace.smart.R;
import com.argrace.smart.base.BaseActivity;
import com.argrace.smart.base.ConstantConfigure;
import com.argrace.smart.callback.StringCallback;
import com.argrace.smart.fragment.MineFragment;
import com.argrace.smart.fragment.QingJingFragment;
import com.argrace.smart.fragment.RoomFragment;
import com.argrace.smart.fragment.WangGuanFragment;
import com.argrace.smart.fragment.YingShiFragment;
import com.argrace.smart.model.LocalDb_QingJingTable;
import com.argrace.smart.model.LocalDb_RoomNameTable;
import com.argrace.smart.ui.ShadeView;
import com.argrace.smart.util.XmlUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.model.HttpHeaders;
import com.lzy.okgo.model.HttpParams;
import com.videogo.openapi.EZOpenSDK;

import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;

public class MainActivity extends BaseActivity implements ViewPager.OnPageChangeListener, View.OnClickListener {
//    EmptyRecycleView recyclerView;
//    SwipeRefreshLayout refreshLayout;
//    DrawerLayout mDrawerLayout;
//    LinearLayout left_ll;
//    TextView userid, loginout;
//    private MyWangGuanAdapter adapter;
//    private ArrayList<WangGuanDeviceEntity> lists = new ArrayList<>();
//    private Handler handler = new Handler();
//    private boolean isFoundDevice = false;
//    OpenAccountUIService openAccountService = OpenAccountSDK.getService(OpenAccountUIService.class);
//
//
//    @Override
//    protected void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_main);
//        init();
//        EnvConfigure.init(this.getApplicationContext());
//    }
//
//
//    private void setView() {
//        recyclerView = (EmptyRecycleView) findViewById(R.id.recyclerView);
//        refreshLayout = (SwipeRefreshLayout) findViewById(R.id.refreshLayout);
//        mDrawerLayout = (DrawerLayout) findViewById(R.id.activity_main_drawerlayout);
//        left_ll = (LinearLayout) findViewById(R.id.activity_main_left_ll);
//        userid = (TextView) findViewById(R.id.activity_main_left_userid);
//        userid.setText(getSharedPreferences(ConstantConfigure.SPLOGIN_NAME, MODE_PRIVATE).getString("id", "default"));
//        loginout = (TextView) findViewById(R.id.activity_main_left_loginout);
//        loginout.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                AlinkLoginBusiness.getInstance().logout(MainActivity.this, new IAlinkLoginCallback() {
//                    @Override
//                    public void onSuccess() {
//                        toastActBtm("登出成功");
//                        SystemClock.sleep(500);
//                        finish();
//                        ChannelBindHelper.getInstance().onLoginChanged(false);
//
//                    }
//
//                    @Override
//                    public void onFailure(int i, String s) {
//                        toastActBtm("登出失败" + s);
//                    }
//                });
//
//
//            }
//        });
//        recyclerView.setItemAnimator(new DefaultItemAnimator());
//        recyclerView.setLayoutManager(new LinearLayoutManager(this));
//        adapter = new MyWangGuanAdapter(lists, this);
//        adapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
//        recyclerView.setAdapter(adapter);
////        refreshLayout.setColorSchemeColors(getResources().getColor(R.color.colorTheme), getResources().getColor(R.color.colorTheme), getResources().getColor(R.color.colorTheme));//getResources().getColor(R.color.colorTheme), getResources().getColor(R.color.colorTheme), getResources().getColor(R.color.colorTheme)
//        refreshLayout.setOnRefreshListener(this);
//        adapter.setListeners(new MyWangGuanAdapter.OnAdapterItemClickListener() {
//            @Override
//            public void click(WangGuanDeviceEntity bean, int position) {
//                Intent intent = new Intent(MainActivity.this, SubDeviceListActivity.class);
//                intent.putExtra("uuid", bean.getUuid());
//                intent.putExtra("model", bean.getModel());
//                startActivity(intent);
//            }
//        });
//        adapter.setlongListeners(new MyWangGuanAdapter.OnAdapterItemLongClickListener() {
//            @Override
//            public void click(WangGuanDeviceEntity bean, int position) {
//                unbind(bean);
//            }
//        });
//    }
//
//    private void init() {
//        login();
//        setView();
//        //设置好初始化内容后，进行登陆操作，没登陆跳登陆界面
//        setTitle(true, false, "我的设备");
//        showRight(true, R.mipmap.head_title_add);
//        //进入搜索网关流程
//        setLeftandRightClickListeners(null, new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                startActivity(new Intent(MainActivity.this, SearchDeviceActivity.class));
//
//            }
//        });
//
//    }
//
//    private void login() {
////        if (AlinkLoginBusiness.getInstance().isLogin()) {
////            Toast.makeText(this, "账号已登录", Toast.LENGTH_SHORT).show();
////        } else {
////            openAccountService.showLogin(MainActivity.this, new LoginCallback() {
////                @Override
////                public void onSuccess(OpenAccountSession openAccountSession) {
////                    editor = spLogin.edit();
////                    editor.putString("token", openAccountSession.getAuthorizationCode());
////                    editor.putString("id", openAccountSession.getAuthorizationCode());
////                    editor.putString("otherinfo", openAccountSession.getAuthorizationCode());
////                    editor.putString("mobile", openAccountSession.getUser().mobile);
////                }
////
////                @Override
////                public void onFailure(int i, String s) {
////                    Log.i("info", "登陆失败");
////                }
////            });
////        }
////        if (AlinkLoginBusiness.getInstance().isLogin()) {
////            Log.i("info", "账号已登陆,userid=" + AlinkLoginBusiness.getInstance().getUserID() + "---seeionid" + AlinkLoginBusiness.getInstance().getSessionID() + "--username" + AlinkLoginBusiness.getInstance().getNickName());
////            Toast.makeText(this, "账号已登录", Toast.LENGTH_SHORT).show();
////        } else {
////            Log.i("info", "账号未登录过，跳转到注册界面");
////            AlinkLoginBusiness.getInstance().login(this, null);
////        }
//    }
//
//    @Override
//    protected void onResume() {
//        super.onResume();
//        onRefresh();
//    }
//
//
//    @Override
//    public void onRefresh() {
//        getMyDevice();
//    }
//
//    @Override
//    public void onLoadMoreRequested() {
//        getMyDevice();
//    }
//
//    public void setRefreshing(final boolean refreshing) {
//        refreshLayout.post(new Runnable() {
//            @Override
//            public void run() {
//                refreshLayout.setRefreshing(refreshing);
//            }
//        });
//    }
//
//    private void getMyDevice() {
//        Log.i("info", "MainActivity.getMyDevice()start");
//        String method = "mtop.openalink.app.core.devices.getbyuser";
//        AlinkHttpUtil.AlinkHttpRequest(method, new HashMap<String, Object>(), new ALinkBusinessEx.IListener() {
//            @Override
//            public void onSuccess(TransitoryRequest transitoryRequest, TransitoryResponse transitoryResponse) {
//                lists.clear();
//                setRefreshing(false);
//                adapter.loadMoreEnd();
//                if (transitoryResponse != null &&transitoryResponse.data != null) {
//                    Log.i("info", "MainActivity.getMyDevice()--success,data=" + transitoryResponse.data.toString());
//                    List<WangGuanDeviceEntity> beans = JSON.parseArray((String) transitoryResponse.data, WangGuanDeviceEntity.class);
//                    lists.addAll(beans);
//                }
//                adapter.notifyDataSetChanged();
//
//            }
//
//            @Override
//            public void onFailed(TransitoryRequest transitoryRequest, AError aError) {
//                setRefreshing(false);
//                adapter.loadMoreEnd();
//                Log.i("info", "MainActivity.getMyDevice()--onFailed,code = " + aError.getCode() + ",msg=" + aError.getMsg());
//            }
//        });
//    }
//
//    private void unbind(WangGuanDeviceEntity device) {
//        Log.i("info", "MainActivity.unbind()start,uuid = " + device.getUuid());
//        String method = "mtop.openalink.app.core.user.unbinddevice";
//        HashMap<String, Object> params = new HashMap<>();
//        params.put("uuid", device.getUuid());
//        AlinkHttpUtil.AlinkHttpRequest(method, params, new ALinkBusinessEx.IListener() {
//            @Override
//            public void onSuccess(TransitoryRequest transitoryRequest, TransitoryResponse transitoryResponse) {
//                Log.i("info", "解绑设备成功,data= " + transitoryResponse.data);
//                toastActBtm("解绑成功");
//                setRefreshing(true);
//                onRefresh();
//            }
//
//            @Override
//            public void onFailed(TransitoryRequest transitoryRequest, AError aError) {
//                Log.i("info", "解绑设备失败,msg= " + aError.getMsg() + aError.getCode());
//                toastActBtm("解绑失败");
//            }
//        });
//    }
//
//    private void loginout() {
//        AlinkLoginBusiness.getInstance().logout(this, new IAlinkLoginCallback() {
//            @Override
//            public void onSuccess() {
//                ChannelBindHelper.getInstance().onLoginChanged(false);
//
//            }
//
//            @Override
//            public void onFailure(int i, String s) {
//
//            }
//        });
//
//    }
//
//    private void setChouTi() {
//        mDrawerLayout.setDrawerListener(new DrawerLayout.DrawerListener() {
//            /** 
//                      * 当抽屉滑动状态改变的时候被调用 
//                      * 状态值是STATE_IDLE（闲置--0）, STATE_DRAGGING（拖拽的--1）, STATE_SETTLING（固定--2）中之一。 
//                      * 抽屉打开的时候，点击抽屉，drawer的状态就会变成STATE_DRAGGING，然后变成STATE_IDLE 
//                     */
//            @Override
//
//            public void onDrawerStateChanged(int arg0) {
//                Log.i("drawer", "drawer的状态：" + arg0);
//            }
//
//            /** 
//                      * 当抽屉被滑动的时候调用此方法 
//                      * arg1 表示 滑动的幅度（0-1） 
//                      */
//            @Override
//            public void
//
//            onDrawerSlide(View arg0, float arg1)
//
//            {
//                Log.i("drawer", arg1 + "");
//            }
//
//            /** 
//                      * 当一个抽屉被完全打开的时候被调用 
//                      */
//            @Override
//            public void onDrawerOpened(View arg0)
//
//            {
//                Log.i("drawer", "抽屉被完全打开了！");
//            }
//
//            /** 
//             * 当一个抽屉完全关闭的时候调用此方法 
//             */
//            @Override
//            public void onDrawerClosed(View arg0)
//
//            {
//                Log.i("drawer", "抽屉被完全关闭了！");
//            }
//        });
//    }


    private Fragment wangguanFragment = new WangGuanFragment();
    private Fragment yingshiFragment = new YingShiFragment();
    private Fragment MineFragment = new MineFragment();
    private Fragment QingjingFragment = new QingJingFragment();
    private Fragment RoomFragment = new RoomFragment();
    private ViewPager viewPager;
    private List<Fragment> fragmentList = new ArrayList<>();
    private List<ShadeView> tabIndicators;
    private FragmentPagerAdapter adapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
        XmlUtils.initPath(this);
        List<LocalDb_QingJingTable> qingjingLists = DataSupport.findAll(LocalDb_QingJingTable.class);
        if (qingjingLists == null || qingjingLists.size() == 0) {
            XmlUtils.readxml(this);
        }
    }


    private void init() {
        setView();
        setTitle(false, false, "我的设备");
        showRight(true, R.mipmap.head_title_add);
        setLeftandRightClickListeners(null, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (viewPager.getCurrentItem() == 0) {
                    startActivity(new Intent(MainActivity.this, SearchDeviceActivity.class));
                }
                if (viewPager.getCurrentItem() == 1) {
                    setTitle(false, false, "我的监控");
                    showRight(true, R.mipmap.head_title_add);
//                    showDialog();
                    showCreateRoomDialog();
                }
                if (viewPager.getCurrentItem() == 2) {
                    Intent intent = new Intent(MainActivity.this, MineGwDeviceListActivity.class);
                    intent.putExtra("type", ConstantConfigure.ACT_TYPE_CHOOSEDEVICE);
                    startActivity(intent);
                }
                if (viewPager.getCurrentItem() == 3) {
                }
            }
        });

    }

    private void setView() {
        viewPager = (ViewPager) findViewById(R.id.activity_main_viewpager);
        viewPager.setOffscreenPageLimit(3);
        viewPager.addOnPageChangeListener(this);
        ShadeView one = (ShadeView) findViewById(R.id.activity_main_tab_one);
        ShadeView two = (ShadeView) findViewById(R.id.activity_main_tab_two);
        ShadeView three = (ShadeView) findViewById(R.id.activity_main_tab_three);
        ShadeView four = (ShadeView) findViewById(R.id.activity_main_tab_four);
        one.setOnClickListener(this);
        two.setOnClickListener(this);
        three.setOnClickListener(this);
        four.setOnClickListener(this);
        tabIndicators = new ArrayList<>();
        tabIndicators.add(one);
        tabIndicators.add(two);
        tabIndicators.add(three);
        tabIndicators.add(four);
        fragmentList.add(wangguanFragment);
//        fragmentList.add(yingshiFragment);
        fragmentList.add(RoomFragment);
        fragmentList.add(QingjingFragment);
        fragmentList.add(MineFragment);
        adapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public int getCount() {
                return fragmentList.size();
            }

            @Override
            public Fragment getItem(int arg0) {
                return fragmentList.get(arg0);
            }
        };
        one.setIconAlpha(1.0f);
        viewPager.setAdapter(adapter);


    }

    @Override
    public void onClick(View v) {
        resetTabsStatus();
        switch (v.getId()) {
            case R.id.activity_main_tab_one:
                tabIndicators.get(0).setIconAlpha(1.0f);
                viewPager.setCurrentItem(0, false);
                break;
            case R.id.activity_main_tab_two:
                tabIndicators.get(1).setIconAlpha(1.0f);
                viewPager.setCurrentItem(1, false);
                break;
            case R.id.activity_main_tab_three:
                tabIndicators.get(2).setIconAlpha(1.0f);
                viewPager.setCurrentItem(2, false);
                break;
            case R.id.activity_main_tab_four:
                tabIndicators.get(3).setIconAlpha(1.0f);
                viewPager.setCurrentItem(3, false);
                break;
        }
    }

    private void resetTabsStatus() {
        for (int i = 0; i < tabIndicators.size(); i++) {
            tabIndicators.get(i).setIconAlpha(0);
        }
    }


    private void showDialog() {
  /*@setView 装入一个EditView
          */
        final EditText editText = new EditText(MainActivity.this);
        AlertDialog.Builder inputDialog =
                new AlertDialog.Builder(MainActivity.this);
        inputDialog.setTitle("请输入序列号和验证码逗号隔开").setView(editText);
        inputDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(MainActivity.this,
                                editText.getText().toString(),
                                Toast.LENGTH_SHORT).show();
                    }
                }).show();
    }

    private void showCreateRoomDialog() {
  /*@setView 装入一个EditView
          */
        final EditText editText = new EditText(MainActivity.this);
        AlertDialog.Builder inputDialog =
                new AlertDialog.Builder(MainActivity.this);
        inputDialog.setTitle("房间名").setView(editText);
        inputDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        LocalDb_RoomNameTable roomNameBean = new LocalDb_RoomNameTable();
                        roomNameBean.setRoomName(editText.getText().toString());
                        int result = roomNameBean.updateAll("roomName = ?", editText.getText().toString());
                        if (result == 0) {
                            roomNameBean.save();
                        }
                    }
                }).show();
    }

    private void addYingShiDevice(String deviceSerialAndvalidateCode) {
        String arg[] = deviceSerialAndvalidateCode.split(",");
        if (arg.length == 2) {
            String deviceSerial = arg[0];
            String validateCode = arg[1];
            String Sub_accessToken = EZOpenSDK.getInstance().getEZAccessToken().getAccessToken();


            HttpParams params = new HttpParams();
            HttpHeaders headers = new HttpHeaders();
            params.put("accessToken", Sub_accessToken);
            params.put("deviceSerial", deviceSerial);
            params.put("validateCode", validateCode);
            OkGo.post("https://open.ys7.com/api/lapp/device/add").tag(this).headers(headers).params(params)
                    .dialogIsShow(false)
                    .tostIsShow(false)
                    .cacheMode(CacheMode.NO_CACHE).execute(new StringCallback() {
                @Override
                public void onSuccess(String s, Call call, Response response) {
                    Log.i("info", "添加设备成功" + s);
                }

                @Override
                public void onError(Call call, Response response, Exception e) {
                    super.onError(call, response, e);
                    Log.i("info", "添加设备失败" + response.toString());
                }
            });


        } else {
            toastActBtm("输入格式错误");
        }
    }
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        Log.e("TAG", "position==" + position);
        Log.e("TAG", "positionOffset==" + positionOffset);
        Log.e("TAG", "positionOffsetPixels==" + positionOffsetPixels);
        if (positionOffset > 0) {
            ShadeView leftTab = tabIndicators.get(position);
            ShadeView rightTab = tabIndicators.get(position + 1);
            leftTab.setIconAlpha(1 - positionOffset);
            rightTab.setIconAlpha(positionOffset);
        }
    }

    @Override
    public void onPageSelected(int position) {
        if (position == 0) {
            setTitle(false, false, "我的设备");
            showRight(true, R.mipmap.head_title_add);
        } else if (position == 1) {
            setTitle(false, true, "我的监控");
            showRight(true, R.mipmap.head_title_add);
        } else if (position == 2) {
            setTitle(false, true, "我的情景");
            showRight(true, R.mipmap.head_title_add);

        } else if (position == 3) {
            setTitle(false, false, "我的设备");

        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
}

class MyFragmentAdapter extends FragmentPagerAdapter {

    List<Fragment> list;

    public MyFragmentAdapter(FragmentManager fm, List<Fragment> list) {
        super(fm);
        this.list = list;
    }

    /**
     * 返回需要展示的fragment
     *
     * @param position
     * @return
     */
    @Override
    public Fragment getItem(int position) {
        return list.get(position);
    }

    /**
     * 返回需要展示的fangment数量
     *
     * @return
     */
    @Override
    public int getCount() {
        return list.size();
    }


}
